package com.mvc.framework.utils;

import com.mvc.framework.entity.XmlBean;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StrutsConfig {

	private StrutsConfig() {
	}

	public static Map<String, XmlBean> readStrutsXml(String xmlPath) throws Exception {
		SAXBuilder builder = new SAXBuilder();
		File xml = new File(xmlPath);
		if (!xml.exists()) {
			throw new RuntimeException("Struts配置文件不存在，文件路径：" + xmlPath);
		}
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();

		Map<String, XmlBean> xmlBeanMap = new HashMap<String, XmlBean>();

		Element actionMappings = root.getChild("action-mapping");
		List<Element> actionList = actionMappings.getChildren();
		for (Element e : actionList) {
			XmlBean xmlBean = new XmlBean();
			String name = e.getAttributeValue("name");
			String actionClazz = e.getAttributeValue("class");
			String reqPath = e.getAttributeValue("reqpath");
			Map<String, String> forwardMap = new HashMap<String, String>();

			Element formBeans = root.getChild("formbeans");
			List<Element> formBeanList = formBeans.getChildren();
			for (Element ex : formBeanList) {
				if (name.equalsIgnoreCase(ex.getAttributeValue("name"))) {
					String beanClass = ex.getAttributeValue("class");
					xmlBean.setBeanName(name);
					xmlBean.setBeanClass(beanClass);
					break;
				}
			}
			xmlBean.setReqpath(reqPath);
			xmlBean.setActionName(name);
			xmlBean.setActionClass(actionClazz);

			List<Element> forwardLsit = e.getChildren();
			for (Element forwardEle : forwardLsit) {
				String fname = forwardEle.getAttributeValue("name");
				String value = forwardEle.getAttributeValue("value");
				forwardMap.put(fname, value);
				xmlBean.setForward(forwardMap);
			}
			xmlBeanMap.put(reqPath, xmlBean);
		}
		return xmlBeanMap;
	}

//	public static void main(String[] args) throws Exception{
//		Map<String, XmlBean> map = StrutsConfig.readStrutsXml("E:\\IDEA_workspace\\mvc\\src\\main\\resource\\struts-config.xml");
//		Set<String> keySet = map.keySet();
//		for (String s : keySet) {
//			XmlBean xmlBean = map.get(s);
//			System.out.println("beanName=" + xmlBean.getBeanName());
//			System.out.println("beanClass=" + xmlBean.getBeanClass());
//			System.out.println("actionName=" + xmlBean.getActionName());
//			System.out.println("actionClass=" + xmlBean.getActionClass());
//			System.out.println("reqPath=" + xmlBean.getReqpath());
//			System.out.println("==============================");
//		}
//	}

}
